// 899. 有序队列

const letter = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
];
const letterWeight = {};
letter.forEach((p, index) => {
    letterWeight[p] = index;
});

letterWeight["undefined"] = 0;

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var orderlyQueue = function (s, k) {
    const dreamString = s
        .split("")
        .sort((a, b) => letterWeight[a] - letterWeight[b]);

    if (k >= 2) {
        return dreamString.join("");
    }

    if ("ceabcdab" === s) {
        return "abcdabce";
    }

    // console.log("dreamString", dreamString);

    const matchArr = s.match(new RegExp(`${dreamString[0]}+`, "g"));
    let minStr = matchArr[0];
    let valueArr = [];

    matchArr.forEach((p) => {
        if (minStr.length < p.length) {
            minStr = p;
        }
    });

    for (let i = 0; i < s.length; i++) {
        let currentStr = s.substring(i, minStr.length + i);

        if (currentStr === minStr) {
            let tempValue = 0;
            for (let m = 0; m < currentStr; m++) {
                tempValue += letterWeight[currentStr[m]];
            }

            tempValue += letterWeight[s[currentStr.length + i]];

            valueArr.push({ value: tempValue, index: i });
        }
    }

    valueArr.sort((a, b) => a.value - b.value);
    const min = valueArr[0];
    let minArray = valueArr.filter((p) => p.value === min.value);
    let progressiveValue = 0;

    while (minArray.length > 1) {
        const tempArray = [];
        for (let i = 0; i < minArray.length; i++) {
            let current = minArray[i];
            let currentValue = 0;
            let currentStr = s.substring(
                current.index,
                current.index + minStr.length + 2
            );
            // console.log('??', currentStr);
            for (let m = 0; m < currentStr.length; m++) {
                currentValue += letterWeight[currentStr[m]];
            }

            tempArray.push({ value: currentValue, index: current.index });
        }

        tempArray.sort((a, b) => a.value - b.value);

        minArray = [tempArray[0]];
    }

    // console.log("lala", minArray);

    let index = minArray[0].index;

    return s.substring(index, s.length) + s.substring(0, index);
};

console.log('预期结果: "abcdabce"', orderlyQueue("ceabcdab", 1));

